package com.ruoyi.common.utils;

import java.util.Random;

/**
 * 获取随机字符串
 */
public class CharUtil {

    public static void main(String[] args) {
        System.out.println(getRandomNum(16));
    }

    /**
     * 获取随机字符串
     *
     * @param num
     * @return
     */
    public static String getRandomString(Integer num) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 获取随机字符串
     *
     * @param num
     * @return
     */
    public static String getRandomNum(Integer num) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 右补位，左对齐
     *
     * @param oriStr   原字符串
     * @param len      目标字符串长度
     * @param fillChar 补位字符
     * @return 目标字符串
     */
    public static String padRight(String oriStr, int len, char fillChar) {
        String str = "";
        int strlen = oriStr.length();
        if (strlen < len) {
            for (int i = 0; i < len - strlen; i++) {
                str = str + fillChar;
            }
        }
        str = str + oriStr;
        return str;
    }

    /**
     * 左补位，右对齐
     *
     * @param oriStr   原字符串
     * @param len      目标字符串长度
     * @param fillChar 补位字符
     * @return 目标字符串
     */
    public static String padLeft(String oriStr, int len, char fillChar) {
        int strlen = oriStr.length();
        String str = "";
        if (strlen < len) {
            for (int i = 0; i < len - strlen; i++) {
                str = str + fillChar;
            }
        }
        str = oriStr + str;
        return str;
    }

    /**
     * 生成24位订单编号 10位日期+(平台号码+支付方式+随机数 14位)
     *
     * @param sourceType 平台编号
     * @param payType    支付编号
     * @return
     */
    public static String generateOrderSn(String sourceType, String payType) {
        StringBuilder stringBud = new StringBuilder();
        stringBud.append(System.currentTimeMillis() / 1000);
        stringBud.append(autoGenericCode(sourceType + payType + getRandomNum(8), 14));
        return stringBud.toString();
    }

    /**
     * 不够位数的在前面补0
     *
     * @param code 数字
     * @param num  保留的位数
     * @return
     */
    private static String autoGenericCode(String code, int num) {
        // d 代表参数为正数型
        return String.format("%0" + num + "d", Long.parseLong(code));
    }
}
